﻿using Game.Entity.Accounts;
using Game.Facade;
using Game.Kernel;
using Game.Utils;
using Game.Web.Pay.WX;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Game.Web.Mobile
{
    public partial class WRegister : System.Web.UI.Page
    {
        #region Fields

        public string Openid { get; set; }
        public string Unionid { get; set; }
        public string Nickname { get; set; }
        public int Sex { get; set; }
        protected readonly int GameId = GameRequest.GetQueryInt("GameID", 0);

        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
           if (IsPostBack) return;
            string spreadUrl = "http://" + GetSpreadUrl() + "/Mobile/Register.aspx";
            SystemStatusInfo mode =
                FacadeManage.aideAccountsFacade.GetSystemStatusInfo(
                    AppConfig.SystemConfigKey.MoblieLogonMode.ToString());
            //未启用微信登录时 直接跳转到手机注册页面
            if (mode == null || mode.StatusValue < 4)
            {
                Response.Redirect(spreadUrl);
               return;
            }

            //开始微信注册请求需要在微信客户端情况下（非客户端时会自动报）
          //  WxJsApiHelper jsApiDown = new WxJsApiHelper(this);

            //调用【网页授权获取用户信息】接口获取用户的openid和access_token
            //修改了下流程 无code 则造url进行跳转 有code 则返回空url 进行下一步
          //  string url = jsApiDown.GetOpenidAndAccessToken();
          //  if (!url.Equals(""))
          //  {
          //      Response.Redirect(url);
          //  }

           // try
           // {
          //     //获取用户信息
           //     jsApiDown.GetUserInfo();
           //     Openid = jsApiDown.openid;
           //     Unionid = jsApiDown.unionid;
           //     Nickname = jsApiDown.nickname;
           //     Sex = jsApiDown.sex;
          //  }
          //  catch (WxPayException ex)
           // {
          //      //写错误日志
          //      Facade.Log.Write(ex.ToString());
          //  }

            //注册帐号 先检查是否有注册
            if (!string.IsNullOrEmpty(Openid) && FacadeManage.aideAccountsFacade.GetAccountsInfoByUserUin(Unionid) ==
                null)
            {
                UserInfo user = new UserInfo
               {
                    NickName = Nickname,
                    Gender = (byte)Sex,
                    RegisterIP = Utility.UserIP
                };
                Message msg = FacadeManage.aideAccountsFacade.RegisterWX(user, GameId.ToString(), Unionid);
                if (!msg.Success)
                {
                    Facade.Log.Write("微信账号注册不成功：" + msg.Content);
                }
            }

            if (mode?.StatusValue == 4) //只开启手机微信登录时
            {
                //跳转下载页面
                Response.Redirect("/Mobile/index.aspx");
                return;
            }
            //跳转二次注册页面
            Response.Redirect(spreadUrl);
        }

        /// <summary>
        /// 通过GameID 重新构造代理注册链接或推广注册链接
        /// </summary>
        /// <returns></returns>
        public string GetSpreadUrl()
        {
            Message msg = FacadeManage.aideAccountsFacade.GetUserGlobalInfo(0, GameId, "");
            string domain = Request.Url.Authority;
            if (!msg.Success) return domain;
            UserInfo info = msg.EntityList[0] as UserInfo;
            if (info == null)
            {
                return domain;
            }
            AccountsAgent agent = FacadeManage.aideAccountsFacade.GetAccountAgentByUserID(info.UserID);
            if (!string.IsNullOrEmpty(agent?.Domain))
            {
                return agent.Domain.Trim();
            }

            int index = domain.IndexOf('.');
            if (Utils.Validate.IsPositiveInt(domain.Substring(0, index)))
            {
                return domain;
            }
            return GameId + domain.Substring(index, (domain.Length - index));
        }
    }
}